<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧仓库树 -->
      <el-col :span="6">
        <div class="tree-container">
          <div class="tree-header">
            <span class="tree-title">仓库列表</span>
            <el-button type="primary" size="mini" @click="openForm(undefined)" v-hasPermi="['storage:warehouse:create']">
              <i class="el-icon-plus"></i> 新增
            </el-button>
          </div>
          <el-tree
            v-loading="treeLoading"
            :data="warehouseTree"
            :props="treeProps"
            node-key="id"
            ref="tree"
            default-expand-all
            highlight-current
            :current-node-key="selectedWarehouseId"
            @node-click="handleNodeClick"
          >
            <template v-slot:default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ data.warehouseName }}</span>
                <span class="tree-node-actions">
                  <el-button type="text" size="mini" @click.stop="openForm(data)" v-hasPermi="['storage:warehouse:update']">
                    <i class="el-icon-edit"></i>
                  </el-button>
                  <el-button  type="text" size="mini" @click.stop="handleWarehouseDelete(data)" v-hasPermi="['storage:warehouse:delete']">
                    <i class="el-icon-delete" style="color: #f00;"></i>
                  </el-button>
                </span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-col>

      <!-- 右侧库位详情列表 -->
      <el-col :span="18">
        <div class="location-container">
          <!-- 搜索工作栏 -->
          <el-form :model="locationQueryParams" ref="locationQueryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
            <el-form-item label="库位编码" prop="storageLocationCode">
              <el-input v-model="locationQueryParams.storageLocationCode" placeholder="请输入库位编码" clearable @keyup.enter.native="handleLocationQuery"/>
            </el-form-item>
            <el-form-item label="库位名称" prop="storageLocationName">
              <el-input v-model="locationQueryParams.storageLocationName" placeholder="请输入库位名称" clearable @keyup.enter.native="handleLocationQuery"/>
            </el-form-item>
            <el-form-item label="库位类型" prop="storageLocationType">
              <el-select v-model="locationQueryParams.storageLocationType" placeholder="请选择库位类型" clearable size="small">
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker v-model="locationQueryParams.createTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleLocationQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetLocationQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 操作工具栏 -->
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openLocationForm(undefined)"
                        v-hasPermi="['storage:location:create']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleLocationExport" :loading="locationExportLoading"
                        v-hasPermi="['storage:location:export']">导出</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="isEmpty(locationCheckedIds)"
                @click="handleLocationDeleteBatch"
                v-hasPermi="['storage:location:delete']"
              >
                批量删除
              </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getLocationList"></right-toolbar>
          </el-row>

          <el-table
            v-loading="locationLoading"
            :data="locationList"
            :stripe="true"
            :show-overflow-tooltip="true"
            @selection-change="handleLocationRowCheckboxChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="库位编码" align="center" prop="storageLocationCode" />
            <el-table-column label="库位名称" align="center" prop="storageLocationName" />
            <el-table-column label="仓库名称" align="center" prop="warehouseName" />
            <el-table-column label="仓库编码" align="center" prop="warehouseCode" />
            <el-table-column label="库位类型" align="center" prop="storageLocationType" />
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
              <template v-slot="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template v-slot="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="openLocationForm(scope.row.id)"
                          v-hasPermi="['storage:location:update']">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleLocationDelete(scope.row)"
                          v-hasPermi="['storage:location:delete']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <pagination v-show="locationTotal > 0" :total="locationTotal" :page.sync="locationQueryParams.pageNo" :limit.sync="locationQueryParams.pageSize"
                      @pagination="getLocationList"/>
        </div>
      </el-col>
    </el-row>

    <!-- 对话框(添加 / 修改仓库) -->
    <WarehouseForm ref="warehouseFormRef" @success="getWarehouseTree"/>

    <!-- 对话框(添加 / 修改库位) -->
    <LocationForm ref="locationFormRef" :warehouseId="selectedWarehouseId" @success="getLocationList"/>
  </div>
</template>

<script>
import * as WarehouseApi from '@/api/storage/warehouse/index.js';
import * as LocationApi from '@/api/storage/location';
import WarehouseForm from './WarehouseForm.vue';
import LocationForm from './LocationForm.vue';

export default {
  name: "WarehouseLocation",
  components: {
    WarehouseForm,
    LocationForm
  },
  data() {
    return {
      // 仓库树数据
      warehouseTree: [],
      // 仓库树加载状态
      treeLoading: false,
      // 仓库树配置
      treeProps: {
        children: 'children',
        label: 'warehouseName'
      },
      // 当前选中的仓库ID
      selectedWarehouseId: null,

      // 库位相关数据
      locationLoading: true,
      locationExportLoading: false,
      showSearch: true,
      locationTotal: 0,
      locationList: [],
      locationCheckedIds: [],
      locationQueryParams: {
        pageNo: 1,
        pageSize: 10,
        warehouseId: null,
        storageLocationCode: null,
        storageLocationName: null,
        storageLocationType: null,
        createTime: []
      }
    };
  },
  created() {
    this.getWarehouseTree();
  },
  methods: {
    /** 获取仓库树数据 */
    async getWarehouseTree() {
      try {
        this.treeLoading = true;
        const params = {
          pageNo: 1,
          pageSize: 1000 // 获取足够多的数据用于构建树
        };
        const res = await WarehouseApi.getWarehousePage(params);
        this.warehouseTree = res.data;

        // 默认选中第一个仓库
        if (this.warehouseTree && this.warehouseTree.length > 0) {
          this.$nextTick(() => {
            const firstNode = this.warehouseTree[0];
            this.$refs.tree.setCurrentKey(firstNode.id);
            this.handleNodeClick(firstNode);
          });
        }
      } finally {
        this.treeLoading = false;
      }
    },

    /** 删除仓库 */
    async handleWarehouseDelete(row) {
      const id = row.id;
      const name = row.warehouseName;
      await this.$modal.confirm(`是否确认删除仓库"${name}"的数据项?`);
      try {
        await WarehouseApi.deleteWarehouse(id);
        await this.getWarehouseTree();
        this.$modal.msgSuccess("删除成功");
      } catch (error) {
        console.error('删除仓库失败:', error);
      }
    },

    /** 处理仓库节点点击 */
    handleNodeClick(nodeData) {
      this.selectedWarehouseId = nodeData.id;
      this.locationQueryParams.warehouseId = nodeData.id;
      this.locationQueryParams.pageNo = 1;
      this.getLocationList();
    },

    /** 查询库位列表 */
    async getLocationList() {
      if (!this.selectedWarehouseId) return;

      try {
        this.locationLoading = true;
        const res = await LocationApi.getLocationPage(this.locationQueryParams);
        this.locationList = res.data.list;
        this.locationTotal = res.data.total;
      } finally {
        this.locationLoading = false;
      }
    },

    /** 库位搜索按钮操作 */
    handleLocationQuery() {
      this.locationQueryParams.pageNo = 1;
      this.getLocationList();
    },

    /** 库位重置按钮操作 */
    resetLocationQuery() {
      this.resetForm("locationQueryForm");
      this.locationQueryParams.warehouseId = this.selectedWarehouseId;
      this.handleLocationQuery();
    },

    /** 打开仓库表单 */
    openForm(id) {
      this.$refs["warehouseFormRef"].open(id);
    },

    /** 打开库位表单 */
    openLocationForm(id) {
      this.$refs["locationFormRef"].open(id);
    },

    /** 删除库位 */
    async handleLocationDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除仓储仓库库位编号为"' + id + '"的数据项?')
      try {
        await LocationApi.deleteLocation(id);
        await this.getLocationList();
        this.$modal.msgSuccess("删除成功");
      } catch {}
    },

    /** 批量删除库位 */
    async handleLocationDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await LocationApi.deleteLocationList(this.locationCheckedIds);
        this.locationCheckedIds = [];
        await this.getLocationList();
        this.$modal.msgSuccess("删除成功");
      } catch {}
    },

    /** 库位选择框变化 */
    handleLocationRowCheckboxChange(records) {
      this.locationCheckedIds = records.map((item) => item.id);
    },

    /** 导出库位数据 */
    async handleLocationExport() {
      await this.$modal.confirm('是否确认导出所有仓储仓库库位数据项?');
      try {
        this.locationExportLoading = true;
        const data = await LocationApi.exportLocationExcel(this.locationQueryParams);
        this.$download.excel(data, '仓储仓库库位.xls');
      } catch {
      } finally {
        this.locationExportLoading = false;
      }
    }
  }
};
</script>

<style scoped>
.tree-container {
  height: 100%;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 10px;
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e6e6e6;
}

/* 仓库列表标题放大样式 */
.tree-title {
  font-size: 18px;
  font-weight: bold;
}

.custom-tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.tree-node-actions {
  visibility: hidden;
}

.custom-tree-node:hover .tree-node-actions {
  visibility: visible;
}

.location-container {
  height: 100%;
  padding: 0 10px;
}

/* 自定义树节点选中状态样式 */
::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #e6f7ff;
  color: #1890ff;
  font-weight: bold;
}

/* 自定义一级节点选中状态样式 */
::v-deep .el-tree--highlight-current .el-tree-node.is-current.is-first-level > .el-tree-node__content {
  background-color: #bae7ff;
  border-left: 3px solid #1890ff;
}
</style>
